package code.oldCode.feishuSpecializedTraining.back_trace;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 26029
 * @date 2025/3/17
 * @description
 */
public class MyBackTrace3 {
    // 93. 复原 IP 地址
    public List<String> restoreIpAddresses(String s) {
        List<String> stringList = new ArrayList<>();
        getIP(0, s, new ArrayList<>(), stringList);
        return stringList;
    }

    public void getIP(int pos, String s, List<Integer> list, List<String> stringList) {
        // 逻辑：有四个且刚好用完，算作答案
        if (pos == s.length() && list.size() == 4) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 4; i++) {
                sb.append(list.get(i));
                if (i != 3)
                    sb.append('.');
            }
            stringList.add(sb.toString());
        }
        // 逻辑：有了四个，但pos != len，后面不用再搞了
        if (list.size() == 4)
            return;
        for (int i = pos; i < s.length(); i++) {
            // 剪枝：三位以上绝对超了
            if (i - pos >= 3)
                break;
            String subString = s.substring(pos, i + 1);
            // 逻辑：用到每一个数字，不能出现(String)"023"->(int)23的情况，直接break，因为后面的循环也符合
            if (subString.charAt(0) == '0' && subString.length() > 1)
                break;
            int parseInt = Integer.parseInt(subString);
            // 逻辑：不在范围内不考虑
            if (parseInt >= 0 && parseInt <= 255) {
                list.add(parseInt);
                getIP(i + 1, s, list, stringList);
                list.remove(list.size() - 1);
            }
        }
    }

    // 78. 子集
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        getSubsets(0, nums, new ArrayList<>(), lists);
        return lists;
    }

    public void getSubsets(int pos, int[] nums, List<Integer> list, List<List<Integer>> lists) {
        lists.add(new ArrayList<>(list));
        for (int i = pos; i < nums.length; i++) {
            list.add(nums[i]);
            getSubsets(i + 1, nums, list, lists);
            list.remove(list.size() - 1);
        }
    }

    // 90. 子集 II
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> lists = new ArrayList<>();
        Arrays.sort(nums);
        getSubsetsWithDup(0, nums, new ArrayList<>(), lists);
        return lists;
    }

    public void getSubsetsWithDup(int pos, int[] nums, List<Integer> list, List<List<Integer>> lists) {
        lists.add(new ArrayList<>(list));
        for (int i = pos; i < nums.length; i++) {
            if (i != pos && nums[i] == nums[i - 1])
                continue;
            list.add(nums[i]);
            getSubsetsWithDup(i + 1, nums, list, lists);
            list.remove(list.size() - 1);
        }
    }
}
